/*
 * Copyright (c) 2025 CAX Conversion Project
 */
package com.comac.ins.isfd.util;

import com.comac.ins.common.core.exception.base.BaseException;
import com.comac.ins.isfd.domain.IsfdModelManagementCard;
import com.comac.ins.isfd.domain.bo.IsfdModelManagementCardBo;
import com.comac.ins.isfd.domain.bo.IsfdModelManagementCardStructBo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class SplitBDFFileIntoChunks {
    public final static String LEFT = "LEFT";
    public final static String RIGHT = "RIGHT";

    /**
     * 可改的单元卡类型
     */
    public final static String P_SHELL = "PSHELL";

    public static List<IsfdModelManagementCard> processBDFFile(String filePath, List<String> typesToProcess, IsfdModelManagementCardStructBo bo) {
        List<IsfdModelManagementCard> cardList = new ArrayList<>();
        // 需要处理的行类型
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String currentLine;
            long number = 0;
            while ((currentLine = br.readLine()) != null) {
                IsfdModelManagementCard managementCard = new IsfdModelManagementCard();
                managementCard.setModelNumber(bo.getModelNumber());
                managementCard.setSectionNumber(bo.getSectionNumber());
                managementCard.setComponentNumber(bo.getComponentNumber());
                managementCard.setPartNumber(bo.getPartNumber());
                managementCard.setVersionNumber(bo.getVersionNumber());
                managementCard.setPartId(bo.getPartId());
                // 解析注释时修改此行
                managementCard.setType("0");
                managementCard.setBatchNumber(bo.getBatchNumber());
                // 检查行是否以指定类型开头
                String matchedType = null;
                // 找到唯一匹配的 type
                for (String type : typesToProcess) {
                    if (currentLine.startsWith(type)) {
                        if (matchedType != null) {
                            // 如果已经匹配到一个，说明存在多个匹配
                            log.warn("Line matches multiple types. Skipping line: {}", currentLine);
                            throw new BaseException("该行匹配多种卡片类型！ 行: " + currentLine);
                        }
                        matchedType = type;
                    }
                }
                // 如果有且仅有一个匹配的 type
                if (matchedType != null) {
                    managementCard.setCardType(matchedType);
                    number += 1;
                    managementCard.setNumber(number);
                    // 分割字符串
                    String[] chunks = splitStringIntoChunks(currentLine, 8, matchedType);
                    managementCard.setPlace1(chunks[0]);
                    managementCard.setPlace2(chunks[1]);
                    managementCard.setPlace3(chunks[2]);
                    managementCard.setPlace4(chunks[3]);
                    managementCard.setPlace5(chunks[4]);
                    managementCard.setPlace6(chunks[5]);
                    managementCard.setPlace7(chunks[6]);
                    managementCard.setPlace8(chunks[7]);
                    managementCard.setPlace9(chunks[8]);
                    managementCard.setPlace10(chunks[9]);
                    cardList.add(managementCard);
                }
            }
        } catch (IOException e) {
            throw new BaseException(e.getMessage());
        }

        return cardList;
    }

    public static String[] splitStringIntoChunks(String s, int chunkSize, String type) {
        String typk = type + " ".repeat(8 - type.length());
        s = s.replaceFirst(typk, "");

        // 校验总长度是否超出 64 字符
        int supportLength = 80;
        if (s.length() > supportLength - 8) {
            throw new BaseException("数据行长度超出10个分格（80个字符）！/n line: " + s);
        }
        // 将字符串补全到 80 个字符
        s = s + " ".repeat(supportLength - 8 - s.length()); // -8 是因为前缀占了 8 字符

        // 计算需要的分组数量
        int numChunks = (int) Math.ceil((double) s.length() / chunkSize);

        // 创建分组数组
        String[] chunks = new String[numChunks + 1];
        // 第一个元素包含类型前缀
        chunks[0] = type;

        // 按每8位进行分割
        for (int i = 0; i < numChunks; i++) {
            int start = i * chunkSize;
            int end = Math.min(start + chunkSize, s.length());
            chunks[i + 1] = s.substring(start, end).trim();
        }
        return chunks;
    }

    /**
     * 补全 8位的占位符
     * LEFT是往左补
     * RIGHT是往右补
     */
    public static String completePlaceStr(String placeStr, String toward) {
        if (StringUtils.isBlank(placeStr) || placeStr.length() > 8) {
            return placeStr;
        }
        if (RIGHT.equals(toward)) {
            return placeStr + " ".repeat(8 - placeStr.length());
        } else if (LEFT.equals(toward)) {
            return " ".repeat(8 - placeStr.length()) + placeStr;
        }
        return placeStr;
    }

//    public static void main(String[] args) {
//        // BDF 文件路径
//        String filePath = "E:\\要素数据库\\结构CAE交付\\C919_10002\\C919_Material_Library.bdf";
//        String line = "GRID    12328001        8270.311-378.9321925.717";
//        String type = "GRID";
//
//        line = "CQUAD4  121323891000581712328625123289921232899012328626             0.0";
//        type = "CQUA4";
//
//        String[] chunks = splitStringIntoChunks(line, 8, type);// 读取 BDF 文件内容并逐行处理
//        for (String chunk : chunks) {
//            System.out.println(chunk);
//        }
//    }
}
